import React, { useState, useEffect, useCallback, useMemo, useRef } from 'react';
import { Table, Button, Modal, Form, Input, Select, message, Spin, Space, Typography, Tag, Pagination, Tooltip, Drawer } from 'antd';
import { PlusOutlined, SettingOutlined } from '@ant-design/icons';
import type { TableProps } from 'antd';
import {
    getGroupList,
    getGroupById,
    addGroup,
    editGroup,
    deleteGroup,
    Group,
    searchGroups,
    GroupForAdd,
    GroupForEdit
} from '@/utils/api/group/group';
import moment from 'moment';
import GroupDetailModal from '@/components/Group/GroupDetailModal';
import GroupSearch from '@/components/Group/search';

const { Title } = Typography;
const { Option } = Select;
const { TextArea } = Input;

interface GroupWithTeachers extends Group {
    teachers?: { name: string }[];
}

interface PaginationResponse {
    list: Group[];
    total: number;
    pages: number;
}

const GroupList: React.FC = () => {
    // 表格数据状态
    const [groups, setGroups] = useState<GroupWithTeachers[]>([]);
    const [total, setTotal] = useState<number>(0);
    const [pages, setPages] = useState<number>(0);
    const [loading, setLoading] = useState<boolean>(false);
    const [currentGroup, setCurrentGroup] = useState<Group | null>(null);
    const [detailModalVisible, setDetailModalVisible] = useState<boolean>(false);
    const [currentGroupId, setCurrentGroupId] = useState<number | null>(null);

    // 搜索状态
    const [searchParams, setSearchParams] = useState<any>({});

    // 分页状态
    const [pagination, setPagination] = useState({
        current: 1,
        pageSize: 10,
    });

    // 可选的页面大小选项
    const pageSizeOptions = useMemo(() => ['10', '20', '50', '100'], []);

    // 模态框状态
    const [visible, setVisible] = useState<boolean>(false);
    const [currentId, setCurrentId] = useState<number | null>(null);

    // 日期时间选择状态
    const [selectedDateTime, setSelectedDateTime] = useState<string>('');

    // 新增/编辑表单
    const [form] = Form.useForm();

    // 请求控制器ref，用于中断请求
    const abortControllerRef = useRef<AbortController | null>(null);

    // 防抖定时器ref
    const debounceRef = useRef<NodeJS.Timeout | null>(null);

    // Drawer状态
    const [drawerVisible, setDrawerVisible] = useState<boolean>(false);
    const [currentGroupRecord, setCurrentGroupRecord] = useState<Group | null>(null);

    // 获取小组数据
    const fetchGroups = useCallback(async (page: number = 1, pageSize: number = 10, params: any = {}) => {
        // 中断之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        // 创建新的AbortController
        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);

            // 判断是否有搜索参数，决定使用哪个API
            const hasSearchParams = Object.keys(params).length > 0;

            let response;
            if (hasSearchParams) {
                // 使用搜索API，参数放在请求体中
                const requestData = {
                    ...params
                };
                // 移除空值
                Object.keys(requestData).forEach(key => {
                    if (requestData[key] === undefined || requestData[key] === '') {
                        delete requestData[key];
                    }
                });

                response = await searchGroups(requestData, {
                    pageNum: page,
                    pageSize: pageSize
                }, { signal: controller.signal });
            } else {
                // 使用普通获取列表API，参数放在URL中
                const requestParams = {
                    pageNum: page,
                    pageSize: pageSize,
                    ...params
                };
                response = await getGroupList(requestParams, { signal: controller.signal });
            }

            // 检查请求是否被中止
            if (controller.signal.aborted) {
                return;
            }

            // 处理响应数据
            const data = response.data as PaginationResponse;

            // 直接使用后端返回的teacherName字段，避免额外请求
            const groupsWithTeachers = data.list.map((group: Group) => ({
                ...group,
                createTime: group.createTime ?
                    moment(group.createTime).format('YYYY-MM-DD HH:mm:ss') :
                    moment().format('YYYY-MM-DD HH:mm:ss'),
                bornTime: group.bornTime ?
                    moment(group.bornTime).format('YYYY-MM-DD') :
                    null,
                // 将teacherName转换为teachers数组
                teachers: group.teacherName ? group.teacherName.map(name => ({ name })) : []
            }));

            setGroups(groupsWithTeachers);
            setTotal(data.total);
            setPages(data.pages);

            setPagination(prev => ({
                ...prev,
                current: page,
                pageSize
            }));
        } catch (error: any) {
            // 如果是中止请求的错误，不显示错误信息
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取小组列表失败:', error);
        } finally {
            setLoading(false);
        }
    }, []);

    // 初始加载数据
    useEffect(() => {
        fetchGroups(pagination.current, pagination.pageSize);

        // 清理函数：组件卸载时中止所有请求
        return () => {
            if (abortControllerRef.current) {
                abortControllerRef.current.abort();
            }
        };
    }, [fetchGroups]);

    // 分页处理函数，保持搜索状态
    const handleTableChange = useCallback((page: number, pageSize?: number) => {
        // 清除之前的防抖定时器
        if (debounceRef.current) {
            clearTimeout(debounceRef.current);
        }

        // 设置新的防抖定时器
        debounceRef.current = setTimeout(() => {
            const newPageSize = pageSize || pagination.pageSize;
            setPagination({
                current: page,
                pageSize: newPageSize,
            });
            fetchGroups(page, newPageSize, searchParams);
        }, 100); // 100ms防抖延迟
    }, [fetchGroups, pagination.pageSize, searchParams]);

    // 添加搜索处理函数
    const handleSearch = useCallback((params: any) => {

        const searchData = {
            ...params
        };

        // 移除空值
        Object.keys(searchData).forEach(key => {
            if (searchData[key] === undefined || searchData[key] === '') {
                delete searchData[key];
            }
        });

        setSearchParams(searchData);
        fetchGroups(1, pagination.pageSize, searchData);
    }, [fetchGroups, pagination.pageSize]);

    // 添加重置处理函数
    const handleReset = useCallback(() => {
        setSearchParams({});
        fetchGroups(1, pagination.pageSize);
    }, [fetchGroups, pagination.pageSize]);

    // 打开新增模态框
    const handleAdd = useCallback(() => {
        setCurrentId(null);
        setCurrentGroup(null);
        setSelectedDateTime('');
        form.resetFields();
        setVisible(true);
    }, [form]);

    // 打开编辑模态框
    const handleEdit = useCallback(async (id: number) => {
        // 中断之前的请求
        if (abortControllerRef.current) {
            abortControllerRef.current.abort();
        }

        // 创建新的AbortController
        const controller = new AbortController();
        abortControllerRef.current = controller;

        try {
            setLoading(true);
            setCurrentId(id);
            const response = await getGroupById(id, { signal: controller.signal });

            // 检查请求是否被中止
            if (controller.signal.aborted) {
                return;
            }

            const group = response.data;

            // 设置当前小组信息
            setCurrentGroup(group);

            if (group.bornTime) {
                const dateOnly = moment(group.bornTime).format('YYYY-MM-DD');
                setSelectedDateTime(dateOnly);

                // 填充表单数据
                form.setFieldsValue({
                    name: group.name,
                    bornTime: dateOnly,
                    profile: group.profile
                });
            } else {
                setSelectedDateTime('');
                form.setFieldsValue({
                    name: group.name,
                    bornTime: '',
                    profile: group.profile
                });
            }

            setVisible(true);
        } catch (error: any) {
            // 如果是中止请求的错误，不显示错误信息
            if (error.name === 'AbortError') {
                console.log('请求被中止');
                return;
            }
            console.error('获取小组详情失败:', error);
        } finally {
            setLoading(false);
        }
    }, [form]);

    // 处理详情按钮点击
    const handleDetail = useCallback((id: number) => {
        setCurrentGroupId(id);
        setDetailModalVisible(true);
    }, []);

    // 提交表单（新增/编辑）
    const handleSubmit = useCallback(async () => {
        try {
            const values = await form.validateFields();
            setLoading(true);

            const formattedBornTime = values.bornTime ?
                moment(values.bornTime).format('YYYY-MM-DD') :
                '';

            const formattedData = {
                ...values,
                bornTime: formattedBornTime
            };

            if (currentId) {
                // 编辑
                const editData: GroupForEdit = {
                    id: currentId,
                    name: formattedData.name,
                    bornTime: formattedData.bornTime,
                    profile: formattedData.profile,
                    hot: currentGroup?.hot || 0,
                    createTime: currentGroup?.createTime || moment().format('YYYY-MM-DD HH:mm:ss')
                };

                try {
                    await editGroup(editData);
                    message.success("编辑成功");
                } catch (error) {
                    console.error('编辑请求失败:', error);
                    throw error;
                }
            } else {
                // 新增
                try {
                    const addData: GroupForAdd = {
                        name: formattedData.name,
                        bornTime: formattedData.bornTime,
                        profile: formattedData.profile
                    };
                    await addGroup(addData);
                    message.success("添加成功");
                } catch (error) {
                    console.error('新增请求失败:', error);
                    throw error;
                } finally {
                    setLoading(false);
                }
            }

            // 刷新列表时保持搜索状态
            fetchGroups(pagination.current, pagination.pageSize, searchParams);
            setVisible(false);
            setCurrentId(null);
            setSelectedDateTime('');

        } catch (error) {
            console.error('操作失败:', error);

        } finally {
            setLoading(false);
        }
    }, [form, currentId, currentGroup, fetchGroups, pagination.current, pagination.pageSize, searchParams]);

    // 删除小组
    const handleDelete = useCallback(async (id: number) => {
        Modal.confirm({
            title: "确认删除",
            content: "确定要删除这个小组吗？此操作不可恢复",
            okText: "确认",
            cancelText: "取消",
            onOk: async () => {
                try {
                    setLoading(true);
                    await deleteGroup(id);
                    message.success("删除成功");

                    // 重新计算分页
                    const currentPage = pagination.current;
                    const isLastItemOnPage = groups.length === 1;

                    // 如果删除的是当前页的最后一条数据，并且不是第一页，则跳转到前一页
                    if (isLastItemOnPage && currentPage > 1) {
                        fetchGroups(currentPage - 1, pagination.pageSize);
                    } else {
                        // 否则重新获取当前页数据
                        fetchGroups(currentPage, pagination.pageSize);
                    }
                } catch (error) {
                    console.error("删除失败:", error);
                } finally {
                    setLoading(false);
                }
            }
        });
    }, [pagination.current, pagination.pageSize, groups.length, fetchGroups]);

    // 显示抽屉
    const showDrawer = useCallback((record: Group) => {
        setCurrentGroupRecord(record);
        setDrawerVisible(true);
    }, []);

    // 关闭抽屉
    const closeDrawer = useCallback(() => {
        setDrawerVisible(false);
        setCurrentGroupRecord(null);
    }, []);

    // 操作按钮点击处理函数
    const handleDrawerAction = useCallback((action: string, record: Group) => {
        closeDrawer();

        switch (action) {
            case 'detail':
                handleDetail(record.id);
                break;
            case 'edit':
                handleEdit(record.id);
                break;
            case 'delete':
                handleDelete(record.id);
                break;
            default:
                break;
        }
    }, [closeDrawer, handleDetail, handleEdit, handleDelete]);

    // 表格列定义
    const columns = useMemo(() => [
        {
            title: '序号',
            key: 'index',
            className: 'table-cell',
            align: 'center',
            render: (text: any, record: Group, index: number) => {
                // 计算序号: (当前页码 - 1) * 每页条数 + 当前行索引 + 1
                const serialNumber = (pagination.current - 1) * pagination.pageSize + index + 1;
                return serialNumber;
            }
        },
        {
            title: '小组名称',
            dataIndex: 'name',
            key: 'name',
            className: 'table-cell',
            align: 'center',
        },
        {
            title: '成立时间',
            dataIndex: 'bornTime',
            key: 'bornTime',
            className: 'table-cell',
            align: 'center',
            render: (bornTime: string) => bornTime ? moment(bornTime).format('YYYY-MM-DD') : '-',
        },
        {
            title: '小组简介',
            dataIndex: 'profile',
            key: 'profile',
            className: 'table-cell',
            align: 'center',
            render: (profile: string) => (
                profile ? (
                    <Tooltip title={profile}>
                <span>
                    {profile.length > 18 ? `${profile.substring(0, 18)}...` : profile}
                </span>
                    </Tooltip>
                ) : '-'
            ),
        },
        {
            title: '当前人数',
            dataIndex: 'number',
            key: 'number',
            className: 'table-cell',
            align: 'center',
            render: (number: number) => (
                <Tag color="green">
                    {number || 0}人
                </Tag>
            ),
        },
        {
            title: '热度',
            dataIndex: 'hot',
            key: 'hot',
            className: 'table-cell',
            align: 'center',
            render: (hot: number) => (
                <Tag color={hot > 0 ? 'red' : 'default'}>
                    {hot}
                </Tag>
            ),
        },
        {
            title: '指导老师',
            key: 'teachers',
            className: 'table-cell',
            align: 'center',
            minWidth: 80,
            render: (record: GroupWithTeachers) => (
                <div>
                    {record.teachers && record.teachers.length > 0 ? (
                        <Tooltip
                            title={record.teachers.map(teacher => teacher.name).join(', ')}
                            placement="topLeft"
                        >
              <span>
                {record.teachers.slice(0, 2).map(teacher => teacher.name).join(', ')}
                  {record.teachers.length > 2 && `等${record.teachers.length}人`}
              </span>
                        </Tooltip>
                    ) : (
                        <span>暂无</span>
                    )}
                </div>
            ),
        },

        {
            title: '操作',
            key: 'action',
            className: 'table-cell',
            align: 'center',
            width: 120,
            render: (_: any, record: Group) => (
                <Button
                    className="operation-menu-btn"
                    size="small"
                    onClick={() => showDrawer(record)}
                >
                    <SettingOutlined style={{ marginRight: 2 }} />
                    操作菜单
                </Button>
            ),
        },
    ], [pagination.current, pagination.pageSize, showDrawer]);

    return (
        <div className="group-list-container" style={{ padding: '20px' }}>
            {/* 添加搜索组件 */}
            <GroupSearch onSearch={handleSearch} onReset={handleReset} />
            {/* 标题和按钮区域 */}
            <div style={{
                display: 'flex',
                justifyContent: 'space-between',
                alignItems: 'center',
                marginBottom: '20px',
                paddingBottom: '10px',
                borderBottom: '1px solid #f0f0f0'
            }}>
                <Title level={4} style={{ margin: 0 }}>小组列表</Title>

                {/* 新增按钮 */}
                <Button
                    type="primary"
                    icon={<PlusOutlined />}
                    onClick={handleAdd}
                    className="add-group-btn"
                >
                    新增小组
                </Button>
            </div>

            {/* 小组表格 */}
            <Spin spinning={loading}>
                <div style={{
                    overflowX: 'auto',
                    borderRadius: '6px',
                    marginBottom: '26px'
                }}>
                    <Table<Group>
                        columns={columns}
                        dataSource={groups}
                        rowKey="id"
                        pagination={false}
                        style={{ minWidth: '800px' }}
                        scroll={{ y: 500, x: 'max-content' }}
                    />
                </div>

                {/* 分页器 */}
                <div style={{
                    display: 'flex',
                    justifyContent: 'flex-end',
                    alignItems: 'center'
                }}>
                    <Pagination
                        current={pagination.current}
                        pageSize={pagination.pageSize}
                        total={total}
                        showSizeChanger
                        pageSizeOptions={pageSizeOptions}
                        showQuickJumper
                        showTotal={(total, range) => `第 ${range[0]}-${range[1]} 条，共 ${total} 条记录`}
                        onChange={handleTableChange}
                        onShowSizeChange={handleTableChange}
                    />
                </div>

            </Spin>

            {/* 操作抽屉 */}
            <Drawer
                title={`操作菜单 - ${currentGroupRecord?.name || ''}`}
                placement="right"
                onClose={closeDrawer}
                open={drawerVisible}
                width={400}
            >
                {currentGroupRecord && (
                    <Space direction="vertical" style={{ width: '100%' }} size="middle">
                        <Button
                            block
                            className="detail-btn"
                            onClick={() => handleDrawerAction('detail', currentGroupRecord)}
                        >
                            详情
                        </Button>
                        <Button
                            block
                            className="edit-btn"
                            onClick={() => handleDrawerAction('edit', currentGroupRecord)}
                        >
                            编辑
                        </Button>
                        <Button
                            block
                            className="delete-btn"
                            onClick={() => handleDrawerAction('delete', currentGroupRecord)}
                        >
                            删除
                        </Button>
                    </Space>
                )}
            </Drawer>

            {/* 新增/编辑模态框 */}
            <Modal
                title={currentId ? "编辑小组" : "新增小组"}
                open={visible}
                onCancel={() => {
                    setVisible(false);
                    setSelectedDateTime('');
                }}
                footer={[
                    <Button key="cancel" onClick={() => {
                        setVisible(false);
                        setSelectedDateTime('');
                    }}>
                        取消
                    </Button>,
                    <Button key="submit" type="primary" loading={loading} onClick={handleSubmit}>
                        确定
                    </Button>,
                ]}
                destroyOnClose={true}
            >
                <Form
                    form={form}
                    layout="vertical"
                >
                    <Form.Item
                        name="name"
                        label="小组名称"
                        rules={[{ required: true, message: '请输入小组名称' }]}
                    >
                        <Input placeholder="请输入小组名称" />
                    </Form.Item>

                    <Form.Item
                        name="bornTime"
                        label="成立时间"
                        rules={[{ required: true, message: '请选择成立时间' }]}
                    >
                        <input
                            type="date"
                            value={selectedDateTime ? moment(selectedDateTime).format('YYYY-MM-DD') : ''}
                            onChange={(e) => {
                                const value = e.target.value;
                                if (value) {
                                    const formattedDateTime = moment(value).format('YYYY-MM-DD');
                                    setSelectedDateTime(value);
                                    form.setFieldsValue({ bornTime: value });
                                } else {
                                    setSelectedDateTime('');
                                    form.setFieldsValue({ bornTime: '' });
                                }
                            }}
                            style={{
                                width: '100%',
                                height: '32px',
                                padding: '4px 11px',
                                border: '1px solid #d9d9d9',
                                borderRadius: '6px',
                                fontSize: '14px',
                                lineHeight: '1.5',
                                transition: 'all 0.3s',
                                boxSizing: 'border-box',
                                outline: 'none'
                            }}
                            onFocus={(e) => {
                                e.target.style.borrowColor = '#40a9ff';
                                e.target.style.boxShadow = '0 0 0 2px rgba(24, 144, 255, 0.2)';
                                e.target.style.borrowRightWidth = '1px';
                            }}
                            onBlur={(e) => {
                                e.target.style.borrowColor = '#d9d9d9';
                                e.target.style.boxShadow = 'none';
                            }}
                            onMouseEnter={(e) => {
                                e.target.style.borrowColor = '#40a9ff';
                            }}
                            onMouseLeave={(e) => {
                                if (!e.target.matches(':focus')) {
                                    e.target.style.borrowColor = '#d9d9d9';
                                }
                            }}
                        />
                    </Form.Item>

                    <Form.Item
                        name="profile"
                        label="小组简介"
                        rules={[{ required: true, message: '请输入小组简介' }]}
                    >
                        <TextArea placeholder="请输入小组简介" rows={4} />
                    </Form.Item>
                    <Form.Item label="创建时间">
                        <Input
                            disabled
                            value={currentId && currentGroup ?
                                moment(currentGroup.createTime).format('YYYY-MM-DD HH:mm:ss') :
                                "系统自动生成"
                            }
                        />
                    </Form.Item>

                </Form>
            </Modal>

            {/* 小组详情模态框 */}
            <GroupDetailModal
                visible={detailModalVisible}
                groupId={currentGroupId}
                onCancel={() => setDetailModalVisible(false)}
            />

            {/* 添加CSS样式 */}
            <style>{`
        .table-cell {
          padding: 12px 16px;
          white-space: nowrap;
          text-align: center;
        }
        .ant-table-thead > tr > th {
          position: sticky;
          top: 0;
          z-index: 1;
          background-color: #fafafa;
          font-weight: 600;
          text-align: center;
        }
        .ant-table-tbody > tr:hover > td {
          background-color: #f5f5f5;
        }
        
        .add-group-btn {
            background: linear-gradient(135deg, #1677ff 0%, #40a9ff 100%) !important;
            border: none !important;
        }
  
        /* 抽屉按钮样式 */
        .ant-drawer-body .ant-btn {
          background: transparent !important;
          border: none !important;
          box-shadow: none !important;
          text-align: left;
          padding: 12px 16px;
          height: auto;
          border-radius: 6px;
          transition: all 0.2s ease;
          color: rgba(0, 0, 0, 0.85);
          font-size: 14px;
          display: flex;
          align-items: center;
          margin-bottom: 4px;
          width: 100%;
          position: relative;
          overflow: hidden;
        }

        /* 按钮悬停效果 */
        .ant-drawer-body .ant-btn:hover {
          background: rgba(24, 144, 255, 0.1) !important;
          color: #1890ff !important;
          transform: translateX(4px);
        }

        /* 按钮激活效果 */
        .ant-drawer-body .ant-btn:active {
          background: rgba(24, 144, 255, 0.2) !important;
          transform: translateX(4px) scale(0.98);
        }

        /* 编辑按钮特殊样式 */
        .ant-drawer-body .edit-btn:hover {
          background: rgba(82, 196, 26, 0.1) !important;
          color: #52c41a !important;
        }
        
        .ant-drawer-body .edit-btn:active {
          background: rgba(82, 196, 26, 0.2) !important;
        }

        /* 删除按钮特殊样式 */
        .ant-drawer-body .delete-btn:hover {
          background: rgba(255, 77, 79, 0.1) !important;
          color: #ff4d4f !important;
        }

        .ant-drawer-body .delete-btn:active {
          background: rgba(255, 77, 79, 0.2) !important;
        }

        /* 操作按钮样式 */
        .operation-menu-btn {
          padding: 2px 7px !important;
          height: 30px !important;
          
          background: linear-gradient(135deg, #00c3f4 0%, #4cd1af 100%) !important;
          border: none !important;
          color: #ffffff !important;
          border-radius: 8px;
          transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
          box-shadow: 
              0 2px 4px rgba(0, 0, 0, 0.2),
              inset 0 1px 0 rgba(255, 255, 255, 0.1);

          display: inline-flex;
          align-items: center;
          justify-content: center;
          font-weight: 500;
          font-size: 13px;
          letter-spacing: 0.3px;
        }

        .operation-menu-btn:hover {
          background: linear-gradient(135deg, #34495e 0%, #56789a 100%) !important;
          color: #ffffff !important;
          transform: translateY(-2px);
          box-shadow: 
              0 4px 10px rgba(0, 0, 0, 0.25),
              inset 0 1px 0 rgba(255, 255, 255, 0.15);
        }

        .operation-menu-btn:active {
          background: linear-gradient(135deg, #243342 0%, #3a5674 100%) !important;
          transform: translateY(0);
          box-shadow: 
              0 2px 4px rgba(0, 0, 0, 0.2),
              inset 0 1px 0 rgba(255, 255, 255, 0.05);
        }

        .operation-menu-btn .anticon {
          font-size: 14px;
          transition: transform 0.2s ease;
        }

        .operation-menu-btn:hover .anticon {
          transform: rotate(30deg);
        }

        .ant-btn-primary {
          transition: all 0.3s ease;
        }
        
        .ant-btn-primary:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 8px rgba(24, 144, 255, 0.3);
        }
        
        .ant-btn-primary:active {
          transform: translateY(0);
        }
      `}</style>
        </div>
    );
};

export default React.memo(GroupList);